package com.core.springSecurity.common;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zql
 * @Description: 路径过滤器
 * @Data: 9:39 2021/7/12
 */
public class AntPathMatcher {
    private static final String MATCH_ALL = "/**";

    public static class  PathMatcher{
        final int length;
        final String subPath;

        public PathMatcher(String subPath){
            assert!subPath.contains("*");
            this.subPath=subPath;
            this.length=subPath.length();
        }

        public boolean matcher(String servletPath){
           return servletPath.startsWith(this.subPath) && (servletPath.length() == this.length || servletPath.charAt(this.length) == '/');
        }
    }

    List<PathMatcher> pathMatcherList =new ArrayList<>();

    public void addMatcher(String ... servletPaths) {
        for (String path : servletPaths) {
            if (path.endsWith(MATCH_ALL)) {
                pathMatcherList.add(new PathMatcher(path.substring(0, path.length() - 3)));
            }else{
                pathMatcherList.add(new PathMatcher(path));
            }
        }
    }

    public  boolean matcher(String servletPath) {//v2/qwe
        for (PathMatcher pathMatcher : pathMatcherList) {
            if (pathMatcher.matcher(servletPath)) {
                return true;
            }
        }
        return false;
    }

}
